package com.wlcorp.forcazamis.business.system.impl;

import java.util.List;

import com.wlcorp.forcazamis.business.system.IRoleService;
import com.wlcorp.forcazamis.dao.system.IRoleDAO;
import com.wlcorp.forcazamis.dao.system.IStaffDAO;
import com.wlcorp.forcazamis.domain.system.Role;
import com.wlcorp.forcazamis.domain.system.Staff;
import com.wlcorp.forcazamis.exception.ServiceException;
import com.wlcorp.forcazamis.sys.BaseService;
import com.wlcorp.forcazamis.sys.util.AppConstant;
import com.wlcorp.forcazamis.sys.util.Validator;

public class RoleServiceImpl extends BaseService implements IRoleService {
	
	private IRoleDAO roleDAO;
	private IStaffDAO staffDAO;
	public void setRoleDAO(IRoleDAO roleDAO) {
		this.roleDAO = roleDAO;
	}
	
	public void setStaffDAO(IStaffDAO staffDAO) {
		this.staffDAO = staffDAO;
	}

	public List<Role> getRoleList(Role role) throws ServiceException {
		return roleDAO.getRoleList(role);
	}

	public Role getRoleById(Long roleId) throws ServiceException {
		if(!Validator.checkValueIsValid(roleId)){
			return null;
		}
		Role role = roleDAO.getRoleById(roleId);
		if(null != role && null != role.getPermission()){
			role.setPermissionArray(role.getPermission().split("\\|"));
		}
		return role;
	}

	public void saveRole(Role role) throws ServiceException {
		StringBuffer permission = new StringBuffer("");
		if(null != role.getPermissionArray()){
			for(int i = 0;i < role.getPermissionArray().length;i++){
				permission.append(role.getPermissionArray()[i]).append("|");
			}
			permission.deleteCharAt(permission.length() - 1);
		}
		role.setPermission(permission.toString());
		roleDAO.saveRole(role);
	}

	public void deleteRole(Role role) throws ServiceException {
		Staff staff = new Staff();
		staff.setRoleId(role.getRoleId());
		Long count = staffDAO.getStaffCount(staff);
		if(count > 0){
			setErrorField(role,AppConstant.BASE_BEAN_STATUS_ERROR,"角色已使用，无法删除！");
			return;
		}
		roleDAO.deleteRole(role);
	}

}
